// const MongoClient = require('mongodb').MongoClient;
// const assert = require('assert');

// // Connection URL
// const url = 'mongodb://127.0.0.1:27017';

// // Database Name
// const dbName = 'myproject';

// // Create a new MongoClient
// const client = new MongoClient(url);

// // Use connect method to connect to the Server
// client.connect(function(err) {
//   if(err) console.log(err)
//   console.log("Connected successfully to server");

//   const db = client.db(dbName);

//   client.close();
// });


let {MongoClient} = require('mongodb')
let url='mongodb://127.0.0.1:27017'   //数据库连接地址
let dbname='user'
let client=new MongoClient(url, {useNewUrlParser: true})  //创建数据库实力

client.connect(err=>{
  if(err){
    console.log('数据库连接失败',err)
    return
  }
  let db=client.db(dbname)   //连接数据库库名
  

  let coll=db.collection('stu')      //应用集和

  // update(coll,client)
  // find(coll,client)
  // deletes(coll,client)
  insert(coll,client)
})


function find(coll,client){
   //查找
  coll.find({}).toArray((err,data)=>{  
    if(err){
      console.log(err)
      client.close()
      return
    }
    console.log(data)
    client.close()
  })
}

function insert(coll,client){
    //增加
  let name=['li','ws','sd']
  for(let i=0;i<3;i++){
    coll.insertOne({name:name[i],age:100},(err,data)=>{
      if(err){
        console.log('插入失败',err)
        return 
      }
      console.log(data)
    })

  }
  client.close()
}

function update(coll,client){
  //修改
  coll.updateOne({name:'ws'},{$set:{age:38}},(err,data)=>{
    if(err){
      console.log('xiugai失败',err)
      return 
    }
    console.log(data)
    client.close()
  })
  
}

function deletes(coll,client){
  coll.deleteOne({name:'张三1'},err=>{
    if(err){
      console.log(err,'错误')
    }
    client.close()
  })
}
